package com.swf.common.i18n;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.swf.common.exception.WebException;

/**
 * description:Web资源实体类
 * @version 1.0 2013-5-8
 * @author shenwf
 */
public class Resource {
	/**
	 * 资源名称
	 */
	private String  name;
	/**
	 * 资源所有语种相应数据
	 */
	private Map<String,String> valueMap = new HashMap<String,String>();
	
	private static Logger logger = LoggerFactory.getLogger(Resource.class);
	
	
	public Resource() {
	}
	/**
	 * 构造函数
	 * @param name 资源名称
	 */
	public Resource(String name) {
		this.name = name;
	}
	/**
	 * 添加某语种对应的显示信息
	 * @param language
	 * 		语种标识，如EN_US
	 * @param value
	 * 		语种对应的显示信息
	 * @throws WebException
	 */
	public void addLanguage(String language,String value){
		if (valueMap.containsKey(language.toUpperCase())){
			logger.error("语言定义["+this.name+"]重复");
		}
		valueMap.put(language.toUpperCase(), value);
	}
	/**
	 * 取得某种语种对应的显示信息
	 * @param language
	 * 		语种标识，如EN_US
	 * @return 此语种对应的显示信息，如果此语种没用设置，则返回资源名称
	 */
	public String getValueAt(String language) {
		if (language == null){
			return this.name;
		}
		String result = (String)valueMap.get(language.toUpperCase());
		if (result == null){
			result = this.name;
		}
		return result;
	}
	/**
	 * 取得资源名称
	 * @return
	 */
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	/**
	 * 输出为xml
	 */
	public String toString() {
		StringBuffer resourceElement = new StringBuffer();
		resourceElement.append("<resource id=\"").append(this.name).append("\">");
		@SuppressWarnings("rawtypes")
		Iterator iter = valueMap.entrySet().iterator();
		while (iter.hasNext()){
			@SuppressWarnings("unchecked")
			Map.Entry<String, String> entry = (Map.Entry<String, String>)iter.next();
			String language = entry.getKey();
			String display = entry.getValue();
			resourceElement.append("<resourceValue id=\"").append(language).append("\">");
			resourceElement.append(display);
			resourceElement.append("</resourceValue>");
		}
		resourceElement.append("</resource>");
		return resourceElement.toString();
	}
	
}
